//
//  JZBMineInfoViewController.m
//  JZB
//
//  Created by  on 2022/8/30.
//

#import "JZBMineInfoViewController.h"
#import "JZBMineCell.h"
#import "JZBInputAlertViewController.h"
@interface JZBMineInfoViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>
@property (strong, nonatomic) IBOutlet UIImageView *img;
@property (strong, nonatomic) IBOutlet UIView *headerView;
@property (nonatomic, strong) NSArray *array;
@end

@implementation JZBMineInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initUI];
}
- (void)initUI{
    self.title = LS(@"我的资料");
    [UIImage imageWithURL:APP.user.headImg block:^(UIImage * _Nonnull image) {
        self.img.image = image;
    }];
    self.array = @[@"我的资料",@"昵称"];
    self.view.backgroundColor = [UIColor whiteColor];
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.scrollEnabled = NO;
    [self.tableView registerNib:[JZBMineCell nib] forCellReuseIdentifier:[JZBMineCell ID]];
    for (NSLayoutConstraint *c in self.view.constraints) {
        if ([c.firstItem isEqual:self.tableView]) {
            c.active = NO;
        }
    }
    NSLayoutConstraint *top = [self.tableView a1:NSLayoutAttributeTop e:NSLayoutRelationEqual t:self.headerView a2:NSLayoutAttributeBottom c:0];
    NSLayoutConstraint *left = [self.tableView a1:NSLayoutAttributeLeft e:NSLayoutRelationEqual t:self.view a2:NSLayoutAttributeLeft c:0];
    NSLayoutConstraint *bottom = [self.tableView a1:NSLayoutAttributeBottom e:NSLayoutRelationEqual t:self.view a2:NSLayoutAttributeBottom c:0];
    NSLayoutConstraint *right = [self.tableView a1:NSLayoutAttributeRight e:NSLayoutRelationEqual t:self.view a2:NSLayoutAttributeRight c:0];
    [self.view addConstraints:@[top,left,bottom,right]];
}
- (void)http:(NSString *)api para:(NSDictionary*)dict{
    WS(self)
    NSMutableString *url = [NSMutableString stringWithFormat:@"%@?",api];
    for (NSString *key in [dict allKeys]) {
        [url appendFormat:@"%@=%@&",key,dict[key]];
    }
    [CCHttp get:[url substringToIndex:url.length-1] para:nil header:nil success:^(id  _Nonnull response) {
        if ([[response valueForKey:@"status"] intValue] != 0) {
            return [RLHud msg:LS(@"错误")];
        }
        if ([api isEqualToString:api_updateName]) {
            APP.user.username = [dict valueForKey:@"username"];
        }else if ([api isEqualToString:api_updateAvatat]){
            APP.user.headImg = [dict valueForKey:@"url"];
        }
        [APP.user bg_saveOrUpdate];
        [weakself initUI];
        [weakself.tableView reloadData];
        [[NSNotificationCenter defaultCenter] postNotificationName:notifyUserUpdate object:nil];
    } fail:^(NSError * _Nonnull error) {}];
}

#pragma mark - 更换头像
- (IBAction)actionForBtn:(UIButton *)sender {
    WS(self)
    [weakself sheet:nil msg:nil sheet:@[@"相机",@"相簿"] sheetBlock:^(int index, NSString *sheetTitle) {
        UIImagePickerController *vc = [[UIImagePickerController alloc] init];
        vc.delegate = self;
        vc.allowsEditing = YES;
        vc.sourceType = index == 0 ? UIImagePickerControllerSourceTypeCamera : UIImagePickerControllerSourceTypePhotoLibrary;
        vc.modalPresentationStyle = UIModalPresentationOverFullScreen;
        [weakself presentViewController:vc animated:YES completion:nil];
    }];
}
#pragma mark - UIImagePickerControllerDelegate / UINavigationControllerDelegate
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [picker dismissViewControllerAnimated:YES completion:nil];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info
{
    UIImage *img = [info valueForKey:UIImagePickerControllerEditedImage];
    NSData *imageData = UIImageJPEGRepresentation(img, 0.5);
    WS(self)
    [CCHttp upload:api_upload para:nil data:imageData progress:^(NSURLSession * _Nonnull session, NSProgress * _Nonnull progress) {
        
    } success:^(id  _Nonnull response) {
        int code = [[response valueForKey:@"code"] intValue];
        NSString *str = code == 0 ? LS(@"上传成功"):LS(@"上传失败");
        if (code == 0) {
            [weakself http:api_updateAvatat para:@{@"url":response[@"data"]}];
        }
        [RLHud msg:str];
    } fail:^(NSError * _Nonnull error) {}];
    [picker dismissViewControllerAnimated:YES completion:^{
        [RLHud startHud:LS(@"上传图片中...")];
    }];
}
#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.array.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    JZBMineCell *cell = [tableView dequeueReusableCellWithIdentifier:[JZBMineCell ID]];
    cell.name.text = LS(self.array[indexPath.row]);
    cell.content.hidden = NO;
    cell.content.text = indexPath.row == 0 ? APP.user.ID:APP.user.username;
    return  cell;
}
#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0;
}
- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return nil;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return nil;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString * str = self.array[indexPath.row];
    if ([str isEqualToString:@"我的资料"]) {
        
    }else if([str isEqualToString:@"昵称"]){
        WS(self)
        JZBInputAlertViewController *vc = [JZBInputAlertViewController new];
        vc.block = ^(NSString * _Nonnull name) {
            [weakself http:api_updateName para:@{@"username":name}];
        };
        [self presentViewController:vc animated:NO completion:nil];
    }
}
@end
